package com.controller;

import com.api.CommonResult;
import com.api.Commons;
import com.entity.*;
import com.entity.table.AddressTableDef;
import com.entity.table.OrdersTableDef;
import com.service.AddressService;
import com.service.OrderProductsService;
import com.service.OrdersService;
import com.service.ProductsService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.List;

@Controller
public class ClientController {
    @Autowired
    AddressService addressService;

    @Autowired
    OrdersService ordersService;

    @Autowired
    OrderProductsService orderProductsService;

    @Autowired
    ProductsService productsService;

    //收货地址页面
    @GetMapping("/address")
    public String address(HttpServletRequest request, ModelMap model){
        //从内存中读取用户信息
        HttpSession session = request.getSession();
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "client/login";
        }
        //使用链式查询，根据用户id查询用户收货地址
        Address fAddress = addressService.queryChain().where(AddressTableDef.ADDRESS.USER_ID.eq(user.getId())).one();
        model.addAttribute("address", fAddress);
        return "client/address";
    }
    //修改收货地址
    @PostMapping("/address/update")
    public String updateAddress(Address fAddress, ModelMap model,HttpServletRequest request) {
        //从内存中读取用户信息
        HttpSession session = request.getSession();
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "client/login";
        }
        fAddress.setUserId(user.getId());
        model.addAttribute("address",fAddress);
        addressService.saveOrUpdate(fAddress);
        return "/client/address";
    }

    //用户基本信息
    @GetMapping("/user")
    public String user_center_info(HttpServletRequest request, ModelMap model){
        //从内存中读取用户信息
        HttpSession session = request.getSession();
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "client/login";
        }
        List<Orders> orderlist=ordersService.queryChain().where(OrdersTableDef.ORDERS.USER_ID.eq(user.getId())).withRelations().list();
        model.addAttribute("users", user);
        model.addAttribute("orderlist", orderlist);
        return "client/user";
    }
    /**
     * 提交订单,添加订单表。
     *
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("placeOrder")
    @ResponseBody
    @Transactional //使用数据库事务管理，若程序执行过程中出错，回滚所有数据库操作
    public CommonResult placeOrder(Products products, HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            Users user = (Users) session.getAttribute("user");
            //读取收货地址
            Address fAddress = addressService.queryChain().where(AddressTableDef.ADDRESS.USER_ID.eq(user.getId())).one();
            //如果用户没有设置收货地址，则跳转到收货地址设置页面
            if (fAddress == null) {
                return CommonResult.failed("/address");
            }
            Orders fOrder = Orders.builder()//订单编号
                    .status("配送中")
                    .orderDate(Commons.nowDate())//下单时间
                    .userId(user.getId())//用户id
                    .totalAmount(products.getPrice().multiply(new BigDecimal(products.getQuantity())))//订单总价
                    .build();
            //数据插入订单表
            ordersService.save(fOrder);
            //添加订单详情记录
            OrderProducts orderProducts = OrderProducts.builder().orderId(fOrder.getId())//订单id
                    .productId(products.getId())//商品名称
                    .quantity(products.getQuantity())//商品数量
                    .orderId(fOrder.getId())//商品介绍
                    .build();
            orderProductsService.save(orderProducts);

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//数据库出错，回滚所有操作
            e.printStackTrace();
            return CommonResult.failed("/login");
        }
        return CommonResult.success("成功提交订单");
    }

    //订单列表
    @GetMapping("/orderList")
    public String orderList(HttpServletRequest request, ModelMap model){
        //从内存中读取用户信息
        HttpSession session = request.getSession();
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "client/login";
        }
        List<Orders> orderlist=ordersService.queryChain().where(OrdersTableDef.ORDERS.USER_ID.eq(user.getId())).withRelations().list();
        model.addAttribute("orderlist", orderlist);
        return "client/order-list";
    }
    //下单成功
    @GetMapping("/orderSuccess")
    public String orderSuccess(HttpServletRequest request, ModelMap model){
        return "client/order-success";
    }

    //    退出登录
    @GetMapping("logout")
    public String logout(HttpSession httpSession){
        httpSession.removeAttribute("user");
        return "client/login";
    }
}
